import * as path from 'path';
import * as fs from 'fs';

const request = require('request');
// ---- 下载类 ---- //
function StreamDownload() {
  // 声明下载过程回调函数
  this.downloadCallback = null;
}

// 下载进度
function getProgress(received, total) {
  if (!total) return -1;
  const percentage = (received * 100) / total;
  return percentage;
};

// 下载过程
StreamDownload.prototype.downloadFile = function (patchUrl, callback) {
  this.downloadCallback = callback; // 注册回调函数

  //const downloadFile = fileName; // 下载文件名称，也可以从外部传进来

  let receivedBytes = 0;
  let totalBytes = 0;

  const req = request({
    method: 'GET',
    uri: patchUrl,
    headers: {
      'cache-control': 'no-cache'
    }
  });

  //const out = fs.createWriteStream(path.join(baseDir, downloadFile));
  //req.pipe(out);

  req.on('response', (data) => {
    // 更新总文件字节大小
    totalBytes = data.headers['content-length'] ?
      parseInt(data.headers['content-length'], 10) :
      void 0;
    // 传回参数：开始时间，总共字节数，请求体，数据
    this.downloadCallback('start', {
      time: process.uptime(),
      totalBytes,
      req,
      data
    });
  });

  req.on('data', (chunk) => {
    // 更新下载的文件块字节大小
    receivedBytes += chunk.length;
    // 返回时间，当前进度，块大小，已接受字节数
    this.downloadCallback(
      'progress', {
        time: process.uptime(),
        progress: getProgress(receivedBytes, totalBytes),
        chunkLen: chunk.length,
        receiveLen: receivedBytes
      }
    );
  });

  req.on('error', (err) => {
    this.downloadCallback('error', {
      err
    });
    this.downloadCallback('finished', {
      ok: false
    });
  });

  req.on('end', () => {
    if (receivedBytes === totalBytes)
      this.downloadCallback('finished', {
        ok: true
      });
    else
      this.downloadCallback('finished', {
        ok: false
      });
  });

};
const streamDownload = new StreamDownload();

export default streamDownload;